/**
 * Created by JetBrains WebStorm.
 * User: denysk
 * Date: 6/8/11
 * Time: 6:10 PM
 * To change this template use File | Settings | File Templates.
 */

Namespace("sketch.framework.commands");

(function(fwk, commands){
    commands.CommandManager = klass(null, {
        _constructor: function(){
            this.stack = [];
            this.index = -1;
            this.properties = new fwk.Properties();
            this.properties.createProperty('canUndo', 'Undo', false);
            this.properties.createProperty('canRedo', 'Redo', false);
        },

        _setProperties: function(canUndo, canRedo){
            this.properties.set("canUndo", canUndo);
            this.properties.set("canRedo", canRedo);
        },

        execute: function(cmd){
            if (cmd.canExecute() === false){
                return;
            }

            var result = cmd.execute(false);
            if (result === false){
                return;
            }
            if (!cmd.transparent()) {
                this.stack[++this.index] = cmd;
                this._setProperties(true, false);
            }
        },

        createAndExecute: function(id){

            function construct(constructor, args) {
                function F() {
                    return constructor.apply(this, args);
                }
                F.prototype = constructor.prototype;
                return new F();
            }

            var cmd = construct(sketch.commands[id], arguments);
            cmd.execute();
            this.stack[++this.index] = cmd;
            this._setProperties(true, false);
        },

        undoPrevious: function(){
            var cmd = this.stack[this.index--];
            cmd.rollback();
            this._setProperties(this.index >= 0, true);
        },

        redoNext: function(){
            var cmd = this.stack[++this.index];
            cmd.execute(true);
            this._setProperties(true, this.index < this.stack.length - 1);
        },

        canUndo: function(){
            return this.properties.canUndo();
        },
        canRedo: function(){
            return this.properties.canRedo();
        }
    });

    fwk.commandManager = new commands.CommandManager();
})(sketch.framework, sketch.framework.commands);
